<template>
  <div class="signature-pad-container">
    <div class="signature-header">
      <span class="signature-title">{{ title }}</span>
      <div class="signature-actions">
        <el-button size="small" @click="clearSignature">
          <el-icon><Delete /></el-icon>
          清除
        </el-button>
        <el-button size="small" type="primary" @click="saveSignature">
          <el-icon><Check /></el-icon>
          保存
        </el-button>
      </div>
    </div>
    
    <div class="signature-canvas-wrapper" :class="{ 'disabled': disabled }">
      <canvas
        ref="canvasRef"
        :width="canvasWidth"
        :height="canvasHeight"
        @mousedown="startDrawing"
        @mousemove="draw"
        @mouseup="stopDrawing"
        @mouseleave="stopDrawing"
        @touchstart="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="stopDrawing"
        class="signature-canvas"
        :class="{ 'canvas-disabled': disabled }"
      ></canvas>
      
      <div v-if="!hasSignature && !disabled" class="signature-placeholder">
        请在此区域签名
      </div>
    </div>
    
    <div class="signature-info">
      <span class="canvas-size">画布大小: {{ canvasWidth }} × {{ canvasHeight }}</span>
      <span v-if="hasSignature" class="signature-status">
        <el-icon color="#67c23a"><SuccessFilled /></el-icon>
        已签名
      </span>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Delete, Check, SuccessFilled } from '@element-plus/icons-vue'

// Props
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  title: {
    type: String,
    default: '电子签名'
  },
  width: {
    type: Number,
    default: 400
  },
  height: {
    type: Number,
    default: 200
  },
  disabled: {
    type: Boolean,
    default: false
  },
  strokeColor: {
    type: String,
    default: '#000000'
  },
  strokeWidth: {
    type: Number,
    default: 2
  },
  backgroundColor: {
    type: String,
    default: '#ffffff'
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'change', 'save', 'clear'])

// Refs
const canvasRef = ref(null)
const canvasWidth = ref(props.width)
const canvasHeight = ref(props.height)
const hasSignature = ref(false)

// Drawing state
const isDrawing = ref(false)
const lastX = ref(0)
const lastY = ref(0)

// Canvas context
let ctx = null

// 初始化画布
const initCanvas = () => {
  const canvas = canvasRef.value
  if (!canvas) return
  
  ctx = canvas.getContext('2d')
  ctx.lineCap = 'round'
  ctx.lineJoin = 'round'
  ctx.strokeStyle = props.strokeColor
  ctx.lineWidth = props.strokeWidth
  
  // 设置背景色
  ctx.fillStyle = props.backgroundColor
  ctx.fillRect(0, 0, canvasWidth.value, canvasHeight.value)
  
  // 如果有初始值，则加载签名
  if (props.modelValue) {
    loadSignature(props.modelValue)
  }
}

// 开始绘制
const startDrawing = (e) => {
  if (props.disabled) return
  
  isDrawing.value = true
  const rect = canvasRef.value.getBoundingClientRect()
  lastX.value = e.clientX - rect.left
  lastY.value = e.clientY - rect.top
  
  // 开始新路径
  ctx.beginPath()
  ctx.moveTo(lastX.value, lastY.value)
}

// 绘制
const draw = (e) => {
  if (!isDrawing.value || props.disabled) return
  
  const rect = canvasRef.value.getBoundingClientRect()
  const currentX = e.clientX - rect.left
  const currentY = e.clientY - rect.top
  
  ctx.lineTo(currentX, currentY)
  ctx.stroke()
  
  lastX.value = currentX
  lastY.value = currentY
  
  hasSignature.value = true
}

// 停止绘制
const stopDrawing = () => {
  if (!isDrawing.value) return
  isDrawing.value = false
  
  // 如果有签名内容，自动保存
  if (hasSignature.value) {
    const dataURL = canvasRef.value.toDataURL('image/png')
    emit('update:modelValue', dataURL)
    emit('change', dataURL)
  }
}

// 处理触摸开始
const handleTouchStart = (e) => {
  e.preventDefault()
  const touch = e.touches[0]
  const mouseEvent = new MouseEvent('mousedown', {
    clientX: touch.clientX,
    clientY: touch.clientY
  })
  canvasRef.value.dispatchEvent(mouseEvent)
}

// 处理触摸移动
const handleTouchMove = (e) => {
  e.preventDefault()
  const touch = e.touches[0]
  const mouseEvent = new MouseEvent('mousemove', {
    clientX: touch.clientX,
    clientY: touch.clientY
  })
  canvasRef.value.dispatchEvent(mouseEvent)
}

// 清除签名
const clearSignature = () => {
  if (!ctx) return
  
  ctx.clearRect(0, 0, canvasWidth.value, canvasHeight.value)
  ctx.fillStyle = props.backgroundColor
  ctx.fillRect(0, 0, canvasWidth.value, canvasHeight.value)
  
  hasSignature.value = false
  emit('update:modelValue', '')
  emit('change', '')
  emit('clear')
  
  ElMessage.success('签名已清除')
}

// 保存签名
const saveSignature = () => {
  if (!hasSignature.value) {
    ElMessage.warning('请先进行签名')
    return
  }
  
  const dataURL = canvasRef.value.toDataURL('image/png')
  emit('update:modelValue', dataURL)
  emit('save', dataURL)
  
  ElMessage.success('签名已保存')
}

// 加载签名
const loadSignature = (dataURL) => {
  if (!dataURL || !ctx) return
  
  const img = new Image()
  img.onload = () => {
    ctx.clearRect(0, 0, canvasWidth.value, canvasHeight.value)
    ctx.drawImage(img, 0, 0, canvasWidth.value, canvasHeight.value)
    hasSignature.value = true
  }
  img.src = dataURL
}

// 获取签名数据
const getSignatureData = () => {
  return canvasRef.value ? canvasRef.value.toDataURL('image/png') : ''
}

// 检查是否为空签名
const isEmpty = () => {
  if (!ctx) return true
  
  const canvasData = ctx.getImageData(0, 0, canvasWidth.value, canvasHeight.value)
  return canvasData.data.every((channel, index) => {
    // Alpha通道
    if ((index + 1) % 4 === 0) {
      return channel === 255 // 完全透明
    }
    // RGB通道应该是背景色
    return channel === 255 // 白色背景
  })
}

// 暴露方法
defineExpose({
  clearSignature,
  saveSignature,
  getSignatureData,
  isEmpty
})

// 监听props变化
watch(() => props.modelValue, (newVal) => {
  if (newVal && newVal !== getSignatureData()) {
    loadSignature(newVal)
  } else if (!newVal) {
    clearSignature()
  }
})

// 组件挂载
onMounted(() => {
  nextTick(() => {
    initCanvas()
  })
})
</script>

<style scoped>
.signature-pad-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background: #fff;
  overflow: hidden;
}

.signature-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
}

.signature-title {
  font-weight: 500;
  color: #303133;
}

.signature-actions {
  display: flex;
  gap: 8px;
}

.signature-canvas-wrapper {
  position: relative;
  background: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.signature-canvas-wrapper.disabled {
  background: #f5f7fa;
  cursor: not-allowed;
}

.signature-canvas {
  border: none;
  cursor: crosshair;
  display: block;
}

.signature-canvas.canvas-disabled {
  cursor: not-allowed;
  opacity: 0.6;
}

.signature-placeholder {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #c0c4cc;
  font-size: 14px;
  pointer-events: none;
  z-index: 1;
}

.signature-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px;
  background: #f9fafc;
  border-top: 1px solid #ebeef5;
  font-size: 12px;
  color: #909399;
}

.canvas-size {
  color: #909399;
}

.signature-status {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #67c23a;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .signature-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .signature-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .signature-canvas {
    max-width: 100%;
    height: auto;
  }
  
  .signature-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
}
</style>
